'use strict';

var debug = require('debug'),
  log = debug('yozh:mw:log'),
  error = debug('yozh:mw:error'),
  verbose = debug('yozh:mw:verbose');

/**
 * querystring middleware
 * use this.query={'search.name': 'name', 'search.age': 12}
 * to this.youzhe.search = {name: 'name', age: 12}
 * @param  {Object} opts options
 * @return {Function} ES6 generator function
 */
module.exports = function(opts) {
  var middleware = function *myQuery(next) {
    if (opts && opts.tools) {
      if (!opts.tools.isEmptyObject(this.query)) {
        var keys = Object.keys(this.query);
        var youzhe = this.youzhe = {};
        for (var key in keys) {
          if (key.indexOf('.') > 0) {
            var skey = key.split('.');
            // need to filter some key;
            var ykey;
            if (youzhe[skey[0]]) {
              ykey = youzhe[skey[0]];
            } else {
              ykey = youzhe[skey[0]] = {};
            }
            log(ykey);
            ykey[skey[1]] = this.query[key];
          }
        }
      }
    }
    yield next;
  };
  return middleware;
};
